﻿using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ThreeTeams.API.Application.Command.ShelvesCommand;
using ThreeTeams.API.DTOs;
using ThreeTeams.Domain;
using ThreeTeams.ErrorCode;
using ThreeTeams.Infrastructure;

namespace ThreeTeams.API.Application.CommandHandler.ShelvesCommandHandler
{
    /// <summary>
    /// 货架查询命令处理器（支持货架号和仓库名称模糊查询，带分页）
    /// </summary>
    public class QueryShelvesCommandHandler : IRequestHandler<QueryShelvesCommand, ApiPaging<ShelvesDto>>
    {
        private readonly IBaseRepository<Shelves> baseRepository;
        public QueryShelvesCommandHandler(IBaseRepository<Shelves> baseRepository)
        {
            this.baseRepository = baseRepository;
        }
        public Task<ApiPaging<ShelvesDto>> Handle(QueryShelvesCommand request, CancellationToken cancellationToken)
        {
            var query = baseRepository.GetAll().Where(x => !x.IsDeleted);
            if (!string.IsNullOrWhiteSpace(request.Code))
                query = query.Where(x => x.Code.Contains(request.Code));
            if (!string.IsNullOrWhiteSpace(request.Name))
                query = query.Where(x => x.Name.Contains(request.Name));

            int totalCount = query.Count();
            int pageSize = request.PageSize > 0 ? request.PageSize : 10;
            int pageIndex = request.PageIndex > 0 ? request.PageIndex : 1;
            int totalPage = (int)System.Math.Ceiling(totalCount / (double)pageSize);

            var list = query
                .OrderBy(x => x.Id)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Select(x => new ShelvesDto
                {
                    Id = x.Id,
                    Name = x.Name,
                    Code = x.Code,
                    BoxCount = x.BoxCount,
                    SkuTypeCount = x.SkuTypeCount,
                    SkuTotalCount = x.SkuTotalCount,
                    Remark = x.Remark
                }).ToList();

            var res = new ApiPaging<ShelvesDto>
            {
                Code = ApiEnum.Ok,
                Message = "查询成功",
                Data = list,
                TotalCount = totalCount,
                TotalPage = totalPage
            };
            return Task.FromResult(res);
        }
    }
}